package com.polaris.live.widget.pag

import android.content.Context
import android.os.CountDownTimer
import android.util.AttributeSet
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import org.libpag.PAGView

/**
 * 封装pag
 *
 * @author Created by 半仙 on 2023/12/5/005 17:28
 */
class PagWidgetView(context: Context, attrs: AttributeSet? = null) : PAGView(context, attrs) {

    private val mLifecycleOwner: LifecycleOwner by lazy {
        context as? LifecycleOwner ?: throw IllegalArgumentException("View context must implement LifecycleOwner")
    }

    //动画开始
    private var mOnPagStartCallback: (() -> Unit)? = null

    //动画结束
    private var mOnPagEndCallback: (() -> Unit)? = null

    private var mTimer: TimeCount? = null

    init {
        //绑定声明周期
        mLifecycleOwner.lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    stopPag()
                }
            }
        })
    }

    fun startPag() {
        if (mLifecycleOwner.lifecycle.currentState == Lifecycle.State.DESTROYED) {
            return
        }

        play()

        cancelTimer()
        mTimer = TimeCount(duration() + DELAY, 1000).apply {
            start()
        }

        mOnPagStartCallback?.invoke()
    }

    override fun onAnimationStart() {
        super.onAnimationStart()
        visibility = VISIBLE
    }

    override fun onAnimationEnd() {
        super.onAnimationEnd()
        visibility = GONE
    }

    fun stopPag() {
        visibility = GONE

        mTimer?.cancel()
        mTimer = null

        mOnPagEndCallback?.invoke()
    }

    private fun cancelTimer() {
        mTimer?.cancel()
        mTimer = null
    }

    internal inner class TimeCount(millisInFuture: Long, countDownInterval: Long) :
        CountDownTimer(millisInFuture, countDownInterval) {

        override fun onTick(millisUntilFinished: Long) {
            if (!isPlaying) {
                stopPag()
            }
        }

        override fun onFinish() {
            stopPag()
        }
    }

    fun setOnPagStartCallback(l: () -> Unit) {
        mOnPagStartCallback = l
    }

    fun setOnPagEndCallback(l: () -> Unit) {
        mOnPagEndCallback = l
    }

    companion object {

        const val DELAY = 5000L
    }
}